using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using UwinEducation.Domain.Entities;
using UwinEducation.Domain.IRepositories;
using UwinEducation.Infrastructure.Persistence;
using UwinEducation.Shared.Models;

namespace UwinEducation.Infrastructure.Repositories
{
    public class UserRepository : Repository<User, Guid>, IUserRepository
    {
        public UserRepository(ApplicationDbContext context) : base(context)
        {
        }

        public async Task<User> GetByUsernameAsync(string username)
        {
            return await _dbSet.AsNoTracking()
                .FirstOrDefaultAsync(u => u.UserName == username);
        }

        public async Task<bool> ExistsByUserNameAsync(string userName, Guid? excludeId = null)
        {
            return await _context.Users
                .AsNoTracking()
                .Where(u => u.UserName == userName && (!excludeId.HasValue || u.Id != excludeId.Value))
                .AnyAsync();
        }

        public async Task<PagedResult<User>> GetPagedListAsync(UserPageRequest pageRequest)
        {

            var query = _context.Users.AsNoTracking().AsQueryable();


            // 如果有搜索条件，添加过滤

            // if (!string.IsNullOrEmpty(pageRequest.Search))
            // {
            //     query = query.Where(r => r.UserName.Contains(pageRequest.Search));
            // }

            if (!string.IsNullOrEmpty(pageRequest.UserName))
            {
                query = query.Where(r => r.UserName.Contains(pageRequest.UserName));
            }
            if (!string.IsNullOrEmpty(pageRequest.RealName))
            {
                query = query.Where(r => r.RealName.Contains(pageRequest.RealName));
            }
            if (!string.IsNullOrEmpty(pageRequest.PhoneNumber))
            {
                query = query.Where(r => r.PhoneNumber.Contains(pageRequest.PhoneNumber));
            }
            if (!string.IsNullOrEmpty(pageRequest.Email))
            {
                query = query.Where(r => r.Email.Contains(pageRequest.Email));
            }
            var total = await query.CountAsync();
            var items = await query
                .Skip((pageRequest.PageIndex - 1) * pageRequest.PageSize)
                .Take(pageRequest.PageSize)
                .ToListAsync();

            return new PagedResult<User>
            {
                Total = total,
                Items = items
            };


            //var query = _context.Users
            //    .AsNoTracking()
            //    .WhereIf(!string.IsNullOrEmpty(pageRequest.Search), u => 
            //        u.UserName.Contains(pageRequest.Search));

            //var total = await query.CountAsync();

            //// 添加排序
            //if (!string.IsNullOrEmpty(pageRequest.SortField))
            //{
            //    query = query.OrderBy(pageRequest.SortField, pageRequest.SortOrder);
            //}
            //else
            //{
            //    query = query.OrderByDescending(u => u.CreatedAt);
            //}

            //var users = await query
            //    .Skip((pageRequest.PageIndex - 1) * pageRequest.PageSize)
            //    .Take(pageRequest.PageSize)
            //    .ToListAsync();

            //// 加载用户角色信息
            //foreach (var user in users)
            //{
            //    user.RoleIds = await _context.UserRoles
            //        .Where(ur => ur.UserId == user.Id)
            //        .Select(ur => ur.RoleId)
            //        .ToListAsync();

            //    user.RoleNames = await _context.UserRoles
            //        .Where(ur => ur.UserId == user.Id)
            //        .Join(_context.Roles,
            //            ur => ur.RoleId,
            //            r => r.Id,
            //            (ur, r) => r.Name)
            //        .ToListAsync();
            //}

            //return new PagedResult<User>
            //{
            //    Items = users,
            //    Total = total
            //};
        }

        public async Task<User> GetDetailsByIdAsync(Guid id)
        {
            var user = await _context.Users
                .AsNoTracking()
                .FirstOrDefaultAsync(u => u.Id == id);

            return user;
        }

        public async Task<List<Guid>> GetRoleIdsAsync(Guid userId)
        {
            return await _context.UserRoles
                .AsNoTracking()
                .Where(ur => ur.UserId == userId)
                .Select(ur => ur.RoleId)
                .ToListAsync();
        }
    }
} 